<?php
/**
 * 连接池封装
 */
namespace lib\pool;

use Swoole\Coroutine\Channel;
 
abstract class abstractPool
{
    private $min;//最少连接数
    private $max;//最大连接数
    private $count;//当前连接数
    protected $connections;//连接池组
    protected $spareTime;//用于空闲连接回收判断
    //数据库配置
    /*protected $dbConfig = array(
        'host' => '127.0.0.1',
        'port' => 3306,
        'user' => 'root',
        'password' => '123456',
        'database' => 'test',
        'charset' => 'utf8',
        'timeout' => 2, //超时时间
    );*/
 
    private $inited = false;
 
    protected abstract function createDb();
 
    public function __construct()
    {
        $this->min = 1;
        $this->max = 10;
        $this->spareTime = 10 * 3600;
        //$this->count = 0;
	    $this->connections = new Channel($this->max + 1);
    }
 
    protected function createObject()
    {
        $obj = null;
        $db = $this->createDb();
        if ($db) {
            $obj = [
                'last_used_time' => time(),
                'db' => $db,
            ];
        }
        return $obj;
    }
 
    /**
     * 初始换最小数量连接池
     * @return $this|null
     */
    public function init(){

        if ($this->inited) {
            return null;
	    }
        for ($i = 0; $i < $this->max; $i++) {
	        $obj = $this->createObject();
	        //$this->count++;
            $this->connections->push($obj);
	    }
        //return $this;
    }
 
    public function getConnection($timeOut = 10){
	    
	    $obj = $this->connections->pop($timeOut);//timeout为出队的最大的等待时间

        return $obj;
    }
 
     /**
      * 回池操作
      */
    public function free($obj){

        if ($obj) {
            $this->connections->push($obj);
        }
    }
}